package com.mata.worktime.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mata.worktime.configuration.shiro.service.PasswordService;
import com.mata.worktime.dao.user.RoleMapper;
import com.mata.worktime.exception.BaseException;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mata.worktime.dao.user.UserMapper;
import com.mata.worktime.entity.user.User;
import com.mata.worktime.entity.user.UserPost;
import com.mata.worktime.entity.user.UserRole;
import com.mata.worktime.enums.ResultEnum;
import com.mata.worktime.service.user.UserPostService;
import com.mata.worktime.service.user.UserRoleService;
import com.mata.worktime.service.user.UserService;
import com.mata.worktime.util.Convert;
import com.mata.worktime.util.security.ShiroUtils;
import sun.security.provider.MD5;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author earthchen
 * @date 2018/9/21
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService
{

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserPostService userPostService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectUserByLoginName(String username)
    {
        return getOne(new QueryWrapper<User>()
            .eq("del_flag",0)
            .eq(StringUtils.isNotBlank(username),"login_name", username));
    }

    @Override
    public User selectUserByPhoneNumber(String phoneNumber)
    {
        return getOne(new QueryWrapper<User>().eq(StringUtils.isNotBlank(phoneNumber),"phonenumber", phoneNumber));
    }

    @Override
    public User selectUserByEmail(String email)
    {
        return getOne(new QueryWrapper<User>().eq(StringUtils.isNotBlank(email),"email", email));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user)
    {
        String userId = user.getUserId();
        user.setUpdateTime(new Date());
        if (userId == null)
        {
            throw new BaseException(ResultEnum.UPDATE_HAVE_TO_ID);
        }
        // 删除用户与角色关联
        userRoleService.remove(new QueryWrapper<UserRole>().eq(userId!=null,"user_id", userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostService.remove(new QueryWrapper<UserPost>().eq(userId!=null,"user_id", userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        // 刷新缓存
        ShiroUtils.clearCachedAuthorizationInfo();
        return updateById(user);
    }

    @Override
    public boolean resetUserPwd(User user)
    {
        user.randomSalt();
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(),
            user.getSalt()));
        return updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserByIds(String ids)
    {
        String[] userIds = Convert.toStrArray(ids);
        List<String> idList = new ArrayList<>();
        for (String userId : userIds)
        {
            if (User.isAdmin(userId))
            {
                throw new BaseException("不允许删除超级管理员用户");
            }
            idList.add(userId);
        }
        // 删除用户角色对应关系
        userRoleService.remove(new QueryWrapper<UserRole>().in("user_id", userIds));
        return removeByIds(idList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveUser(User user)
    {
        user.randomSalt();
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(),
            user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setCreateTime(new Date());
        if(StringUtils.isBlank(user.getId())){
            user.setId(new Date().getTime() + "");
        }
        save(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        ShiroUtils.clearCachedAuthorizationInfo();
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(User user)
    {
        // 新增用户与角色管理
        List<UserRole> list = new ArrayList<>();
        for (Long roleId : user.getRoleIds())
        {
            UserRole ur = new UserRole();
            ur.setUserId(user.getUserId());
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.size() > 0)
        {
            userRoleService.saveBatch(list);
        }

    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(User user)
    {
        // 新增用户与岗位管理
        List<UserPost> list = new ArrayList<>();
        for (Long postId : user.getPostIds())
        {
            UserPost up = new UserPost();
            up.setUserId(user.getUserId());
            up.setPostId(postId);
            list.add(up);
        }
        if (list.size() > 0)
        {
            userPostService.saveBatch(list);
        }
    }

    @Override
    public User selectUserByLoginUserId(String userId){
        return getOne(new QueryWrapper<User>()
                .eq("del_flag",0)
                .eq(StringUtils.isNotBlank(userId),"id", userId));
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public void insertByList(List<User> insertList) {
        userMapper.insertByList(insertList);
        // 新增用户与岗位管理
        List<UserPost> list1 = new ArrayList<>();
        // 插入后默认给普通用户的角色
        List<UserRole> list2 = new ArrayList<>();
        for (User user : insertList) {
            UserRole ur = new UserRole();
            ur.setUserId(user.getUserId());
            /*
             * 1059280077273116674 为普通用户角色ID
             */
            ur.setRoleId(1059280077273116674L);
            UserPost up = new UserPost();
            up.setUserId(user.getUserId());
            /*
             *  4 为普通用户岗位ID
             */
            up.setPostId(4L);
            list1.add(up);
            list2.add(ur);
        }
        if (list1.size() > 0)
        {
            userPostService.saveBatch(list1);
        }
        if (list2.size() > 0)
        {
            userRoleService.saveBatch(list2);
        }
    }
}
